<!-- 模板 -->
<template>
  <div class="wrapper">
    <h1>单文件组件</h1>
    <cart>
      <!-- 这里的 index 和 product 都是 prop attribute -->
      <cart-item 
                v-for="(p,i) in products" 
                :index="i" 
                :product="p" 
                :key="p.id"
                @product:reduce="handleReduce"
                @product:increase="handleIncrease"
                @product:change="handleChange"></cart-item>
      <total>{{total}}</total>
    </cart>
  </div>
</template>

<!-- 脚本 -->
<script>
// 导入单文件组件
import Cart from './components/Cart.vue' ;
import CartItem from './components/CartItem.vue' ;
import Total from './components/Total.vue' ;

// ES6 提供的导出支持 
export default {
  name: 'App',
  // 局部注册组件
  components: {
    'cart': Cart,
    'cart-item': CartItem ,
    'total': Total
  },
  data(){
    return {
      products: [
                { id: 1234 , name: 'Vue从入门到放弃' , price: 98 , number: 1 },
                { id: 2345 , name: '哈尔冰红肠' , price: 28 , number: 1 },
                { id: 1122 , name: 'SpringBoot从没入门到放弃' , price: 88 , number: 1 },
                { id: 3344 , name: '雪花啤酒(勇闯天涯)' , price: 60 , number: 1 }
                ]
    }
  },
  methods: {
    handleReduce(id){
          console.log( 'handleReduce: ' , id );
          // 根据商品编号从数组中查找指定的商品
          let product = this.products.find( p => p.id == id );
          // 若 product 存在则为 true
          if( product ) {
              if( product.number > 1 ) {
                  product.number-- ;
              }
          }
    },
    handleIncrease(id){
          console.log( 'handleIncrease: ' , id );
          // 根据商品编号从数组中查找指定的商品
          let product = this.products.find( p => p.id == id );
          // 若 product 存在则为 true
          if( product ) {
              product.number++ ;
          }
    },
    handleChange(params){
      let p = this.products.find( p => params.id == p.id );
      console.log( `商品${p.id}的原数量是${p.number}，修改后的数量是${params.number}` );
      p.number = params.number ;
    }
  },
  computed: {
    total(){
      let t = 0 ;
      this.products.forEach( p => {
        t += p.price * p.number ;
      });
      return t ;
    }
  }
}
</script>

<!-- 样式 -->
<style scoped>
h1 { 
  text-align: center;
}
</style>
